require "scripts.少年光头.Helper.deepcopy"

GTBar = require "scripts.少年光头.Helper.classic":extend()
---unit 触发单位
---x 偏移x
---y 偏移y
---z 高度
---id def:'GTHP'(血条)
---color :--PLAYER_COLOR_RED
---animate id
---triggerUnit 血条在谁头上的单位
function GTBar:new(args)
    args = args or {}
    args = deep_copy(args)
    args.x = args.x or -14.57
    args.y = args.y or 0
    args.h = args.h or 110

    self.id = args.id or "GTHP"
    self.x = args.x
    self.y = args.y
    self.h = args.h
    self.triggerUnit = args.triggerUnit
    self.color = args.color

    self:hpSetPosition(self.triggerUnit)
    return self
end
---设置动画
function GTBar:setAnimate(id)
    hunit.animate(self.hpUnit, id)
    return self
end
---设置颜色
---color:--PLAYER_COLOR_RED
function GTBar:setColor(color)
    cj.SetUnitColor(self.hpUnit, color)
    return self
end
---设置Z
function GTBar:setH(z)
    hunit.setFlyHeight(self.hpUnit, z, 0)
    return self
end
---血条绑定单位
function GTBar:hpSetPosition(unit)
    self.triggerUnit = unit
    if self.triggerUnit == nil then
        return
    end
    if self.hpUnit == nil then
        self.hpUnit =
            hunit.create(
            {
                whichPlayer = hunit.getOwner(self.triggerUnit),
                id = hslk.n2i(self.id),
                x = self.x,
                y = self.y,
                isOpenSlot = false,
                isUnSelectable = true,
                isShadow = true,
                isPause = false,
                timeScale = 100
            }
        )
        if self.color ~= nil then
            self.setColor(self.color)
        end
        if self.animate ~= nil then
            self:setAnimate(self.animate)
        else
            self:setAnimate(100)
        end
        self:setH(self.h)
    end

    self.hpPositionTime =
        htime.setInterval(
        0.03,
        function(t)
            -- print_mbr(his.deleted(self.triggerUnit))
            -- print_mbr(his.dead(self.triggerUnit))
            -- print_mbr(his.alive(self.triggerUnit))

            if his.deleted(self.triggerUnit) or his.dead(self.triggerUnit) then
                print_mb("单位不存在注销模拟血条")
                self:destroy()
            else
                cj.SetUnitPosition(self.hpUnit, hunit.x(self.triggerUnit) + self.x, hunit.y(self.triggerUnit) + self.y)
                self:triggerUnitHPUpdate()
                local h = hunit.getFlyHeight(self.triggerUnit)
                self:setH(h + self.h)
            end
        end
    )

    return self
end
---血量变动更新
function GTBar:triggerUnitHPUpdate()
    --最大生命值
    local MaxLife = hunit.getMaxLife(self.triggerUnit)
    --当前生命值
    local CurLife = hunit.getCurLife(self.triggerUnit)
    if CurLife ~= MaxLife then
        local id = math.ceil((CurLife / MaxLife) * 100)
        self:setAnimate(id)
    end
    return self
end
---销毁
function GTBar:destroy()
    hunit.del(self.hpUnit)
    self.hpPositionTime.destroy()
    return self
end
